<template>
	<view class="container ptb_8 plr_15 pbsafe_56">
		<view class="bc_fff br_8 plr_12">
			<u--form labelPosition="left" labelWidth="auto" :model="formData" :rules="rules" ref="uForm">
				<u-form-item required label="经销商名称" prop="dealerName" borderBottom ref="item1">
					<u--input inputAlign="right" placeholder="请输入经销商名称" v-model="formData.dealerName"
						border="none"></u--input>
				</u-form-item>
				<u-form-item required label="联系人" prop="contactPerson" borderBottom ref="item1">
					<u--input inputAlign="right" placeholder="请输入联系人" v-model="formData.contactPerson"
						border="none"></u--input>
				</u-form-item>
				<u-form-item required label="联系电话" prop="contactPhone" borderBottom ref="item1">
					<u--input type="number" inputAlign="right" placeholder="请输入联系电话" v-model="formData.contactPhone"
						border="none"></u--input>
				</u-form-item>
				<u-form-item required label="营业执照" prop="businessLicense" borderBottom ref="item1" labelPosition="top">
					<u-upload imageMode="aspectFit" maxCount="1" width="196" height="196"
						:fileList="formData.businessLicense" @afterRead="afterRead" @delete="deletePic"
						name="businessLicense">
						<view class="fx fx_col aic jcc width_98 height_98 bo_1 boc_999 br_4 mt_8 box"
							style="border-style: dashed;">
							<u-icon name="camera-fill" size="48rpx" color="#999999">
							</u-icon>
							<view class="fc_999 fz_12 mt_8">
								上传图片
							</view>
						</view>
					</u-upload>
				</u-form-item>
				<u-form-item label="法人身份证正反面" ref="item1" labelPosition="top">
					<view class="fx jcb">
						<view class="pr br_8 flow_h mt_8">
							<u-upload imageMode="aspectFit" width="300" height="222" maxCount="1"
								:fileList="formData.list2" @afterRead="afterRead" @delete="deletePic" name="list2">
								<image class="width_150 height_111" src="@/static/images/idcard_1.png"></image>
							</u-upload>
							<view class="fc bc_primary fc_fff lh_32">
								身份证人像面
							</view>
						</view>
						<view class="pr br_8 flow_h mt_8">
							<u-upload imageMode="aspectFit" width="300" height="222" maxCount="1"
								:fileList="formData.list3" @afterRead="afterRead" @delete="deletePic" name="list3">
								<image class="width_150 height_111" src="@/static/images/idcard_2.png"></image>
							</u-upload>
							<view class="fc bc_primary fc_fff lh_32">
								身份证国徽面
							</view>
						</view>
					</view>
				</u-form-item>
				<u-form-item label="店铺地址" prop="shopAddress" borderBottom ref="item1">
					<u--input inputAlign="right" placeholder="请输入店铺地址" v-model="formData.shopAddress"
						border="none"></u--input>
				</u-form-item>
				<u-form-item label="店铺照片" prop="shopPhoto" ref="item1" labelPosition="top">
					<u-upload multiple :maxCount="5" width="196" height="196" :fileList="formData.shopPhoto"
						@afterRead="afterRead" @delete="deletePic" name="shopPhoto">
						<view class="fx fx_col aic jcc width_98 height_98 bo_1 boc_999 br_4 mt_8 box"
							style="border-style: dashed;">
							<u-icon name="camera-fill" size="48rpx" color="#999999">
							</u-icon>
							<view class="fc_999 fz_12 mt_8">
								上传图片
							</view>
						</view>
					</u-upload>
				</u-form-item>
			</u--form>
		</view>
		<view class="pf b_0 l_0 r_0 pt_8 pbsafe_8 plr_16 bc_fff zi_10">
			<button class="w100 custom_btn primary lh_40 fz_14 br_57" @click="handleSubmit">提交认证</button>
		</view>
	</view>
</template>

<script>
	import api from "@/service/config/api";
	import {
		BASE
	} from '@/const/base'
	export default {
		data() {
			return {
				formData: {
					dealerName: "",
					contactPerson: '',
					contactPhone: '',
					businessLicense: [],
					list2: [],
					list3: [],
					shopAddress: "",
					shopPhoto: []
				},
				rules: {
					'dealerName': {
						type: 'string',
						required: true,
						message: '请输入经销商名称',
						trigger: ['blur', 'change']
					},
					'contactPerson': {
						type: 'string',
						required: true,
						message: '请输入联系人',
						trigger: ['blur', 'change']
					},
					'contactPhone': [{
						type: 'string',
						required: true,
						message: '请输入联系电话',
						trigger: ['blur', 'change'],

					}, {
						// 自定义验证函数，见上说明
						validator: (rule, value, callback) => {
							if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(value)) {
								return uni.$u.test.mobile(value);
							}
							// 上面有说，返回true表示校验通过，返回false表示不通过
							// uni.$u.test.mobile()就是返回true或者false的

						},
						message: '请输入正确的手机号码',
						// 触发器可以同时用blur和change
						trigger: ['change', 'blur'],
					}],

					'businessLicense': [{
						validator: (rule, value, callback) => {
							console.log('valuevaluevalue---', value)
							// 上面有说，返回true表示校验通过，返回false表示不通过
							// uni.$u.test.mobile()就是返回true或者false的
							return value.length > 0;
						},
						message: '请上传营业执照',
						// 触发器可以同时用blur和change
						trigger: ['change', 'blur'],
					}],
					// 'list2': [{
					// 		required: true,
					// 		type: 'array',
					// 		message: '请上传身份证人像面',
					// 		trigger: ['blur', 'change']
					// 	},
					// 	{
					// 		validator: (rule, value, callback) => {
					// 			console.log("图片验证")
					// 			console.log(value)
					// 			return value.length > 0

					// 		}
					// 	}
					// ],
					// 'shopPhoto': [{
					// 		required: true,
					// 		type: 'array',
					// 		message: '请上传身份证国徽面',
					// 		trigger: ['blur', 'change']
					// 	},
					// 	{
					// 		validator: (rule, value, callback) => {
					// 			return value.length > 0
					// 			console.log("图片验证")
					// 			console.log(value)

					// 		}
					// 	}
					// ]
				},
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules)
		},
		onLoad(options) {
			if (options.edit) {
				this.getData()
			}
		},
		methods: {
			getData() {
				this.$utils.loading()
				api.get('/user/api/dealer/info').then(res => {
					const {
						dealerName,
						contactPerson,
						contactPhone,
						businessLicense,
						shopAddress,
						shopPhoto,
						corporateIdentityPhoto
					} = res.data
					this.formData = {
						dealerName,
						contactPerson,
						contactPhone,
						shopAddress,
						businessLicense: businessLicense ? businessLicense.split(',').map(item => this
							.formatUploadImg(item)) : [],
						shopPhoto: shopPhoto ? shopPhoto.split(',').map(item => this.formatUploadImg(item)) :
						[],
						list2: corporateIdentityPhoto ? [this.formatUploadImg(corporateIdentityPhoto.split(
							',')[0])] : [],
						list3: corporateIdentityPhoto ? [this.formatUploadImg(corporateIdentityPhoto.split(
							',')[1])] : []
					}
				})
			},
			formatUploadImg(item) {
				return {
					url: item,
					status: 'success',
					message: '',
				}
			},
			// 删除图片
			deletePic(event) {
				this.formData[`${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				console.log(9999)
				console.log(event)
				console.log(Array.isArray(event.file))
				console.log(event.file)
				let lists = []
				if (event.name=="shopPhoto") {
					console.log(11)
					lists = [...event.file]
				}else {
					lists.push(event.file)
				}
				// let lists = [event.file]
				console.log(lists)
				let fileListLen = this.formData[`${event.name}`].length
				console.log('fileListLen---', this.formData[`${event.name}`])
				try {
					lists.map((item) => {
						this.formData[`${event.name}`].push({
							...item,
							status: 'uploading',
							message: '上传中'
						})
					})
					for (let i = 0; i < lists.length; i++) {
						const result = await this.uploadFilePromise(lists[i], event.name)
						let item = this.formData[`${event.name}`][fileListLen]
						this.formData[`${event.name}`].splice(fileListLen, 1, Object.assign(item, {
							status: 'success',
							message: '',
							url: result
						}))
						fileListLen++
					}
					this.$forceUpdate()
				} catch (err) {
					this.$utils.showToast(err)
					this.$set(this.formData, event.name, this.formData[`${event.name}`].slice(0, fileListLen))
					console.log(err)
				}
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				console.log(9999)
				console.log(event)
				// let lists = [event.file]
				let lists = []
				if (event.name=="shopPhoto") {
					console.log(11)
					lists = [...event.file]
				}else {
					lists = [event.file]
				}
				console.log(lists)
				let fileListLen = this.formData[`${event.name}`].length
				console.log('fileListLen---', this.formData[`${event.name}`])
				try {
					lists.map((item) => {
						this.formData[`${event.name}`].push({
							...item,
							status: 'uploading',
							message: '上传中'
						})
					})
					for (let i = 0; i < lists.length; i++) {
						const result = await this.uploadFilePromise(lists[i])
						let item = this.formData[`${event.name}`][fileListLen]
						this.formData[`${event.name}`].splice(fileListLen, 1, Object.assign(item, {
							status: 'success',
							message: '',
							url: result
						}))
						fileListLen++
					}
					this.$forceUpdate()
				} catch (err) {
					this.$utils.showToast(err)
					this.$set(this.formData, event.name, this.formData[`${event.name}`].slice(0, fileListLen))
					console.log(err)
				}
			},
			uploadFilePromise(file) {
				console.log("开始上传呢")
				console.log(file)
				let token = `${uni.getStorageSync('tokenType')} ${uni.getStorageSync('token')}`
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: BASE.BASE_URL + '/admin/sys-file/upload', //仅为示例，非真实的接口地址
						header: {
							'Authorization': token,
							'Tenant-Id': uni.getStorageSync("tenantId"),
						},
						name: 'file',
						file: file,
						filePath: file.url,
						success: (res) => {
							if (res.data) {
								const data = JSON.parse(res.data)
								if (data.data && data.data.url) {
									resolve(data.data.url)
								} else {
									reject('上传失败1')
								}
							} else {
								reject('上传失败2')
							}
						},
						fail: (err) => {
							reject('上传失败3')
						}
					});
					// let a = uni.uploadFile({
					// 	url: 'http://192.168.2.21:7001/upload', // 仅为示例，非真实的接口地址
					// 	filePath: url,
					// 	name: 'file',
					// 	formData: {
					// 		user: 'test'
					// 	},
					// 	success: (res) => {
					// 		setTimeout(() => {
					// 			resolve(res.data.data)
					// 		}, 1000)
					// 	}
					// });
					// resolve()
				})
			},
			handleSubmit() {
				console.log(this.formData)
				this.$refs.uForm.validate().then(res => {
					const {
						dealerName,
						contactPerson,
						contactPhone,
						businessLicense,
						list2,
						list3,
						shopAddress,
						shopPhoto
					} = {
						...this.formData
					}
					api.post("/user/api/dealer/submitAuth", {
						dealerName,
						contactPerson,
						contactPhone,
						businessLicense: (businessLicense && businessLicense.length) ? businessLicense[0]
							.url : '',
						corporateIdentityPhoto: ((list2 && list2.length) ? list2[0].url : '') + "," + ((
							list3 && list3.length) ? list3[0].url : ''),
						shopAddress,
						shopPhoto: (shopPhoto && shopPhoto.length) ? shopPhoto[0].url : ''

					}).then(res => {
						if (res && res.code == 0) {
							uni.redirectTo({
								url: "/pages/common/pages/submitSuccess"
							})
						}
						// if (res && res.code == 0) {
						// 	uni.reLaunch({
						// 		url: "/page/index/user"
						// 	})
						// } else {
						// 	uni.$u.toast(res.msg)
						// 	uni.reLaunch({
						// 		url: "/page/index/user"
						// 	})
						// }
					})
				}).catch(errors => {
					// uni.$u.toast('请填写完整的信息')
				})
			}
		}
	}
</script>

<style lang="scss">
	.u-upload__deletable__icon .u-icon__icon,
	.u-upload__success .u-icon__icon {
		font-size: 24rpx !important;
		line-height: 24rpx !important;
	}

	.u-upload__wrap__preview {
		// margin: 0 !important;
	}
</style>

<style lang="scss" scoped>
	.container {}
</style>